<template>
  <a-card :bordered="false" style="height: 100%;">
    <a-spin :spinning="loading">
      <a-tree
        showLine
        :expandedKeys.sync="expandedKeys"
        :selectedKeys="selectedKeys"
        :treeData="treeDataSource"
        @select="handleTreeSelect"
      />
    </a-spin>
  </a-card>
</template>

<script>

  import { getAction } from '@/api/manage'
  import YchConstant from "@/api/YchConstant";

  export default {
    name: 'SelectUserTreeLeft',
    props: {
      value: {
        type: String,
        default: null
      }
    },
    data () {
      return {
        loading: false,
        treeDataSource: [],
        expandedKeys: [],
        url: {
          list: YchConstant.PREFIX_BPM + '/bpm-back/processSelectRest/queryDeptTreeList/v1',
        }
      }
    },
    created () {
      this.queryTreeData()
    },
    computed: {
      selectedKeys () {
        return this.value ? [this.value] : []
      }
    },
    methods: {
      queryDepartTreeList (params) {
        return getAction(this.url.list, params)
      },
      queryTreeData (keyword) {
        this.commonRequestThen(this.queryDepartTreeList({
          departName: keyword ? keyword : undefined
        }))
      },
      handleTreeSelect (selectedKeys, event) {
        this.$emit('input', event.node.dataRef.attributes.deptId)
      },
      commonRequestThen (promise) {
        this.loading = true
        promise.then(res => {
          if (res.success) {
            this.treeDataSource = res.result
            // 默认选中第一条数据、默认展开所有第一级
            if (this.treeDataSource.length > 0) {
              this.expandedKeys = res.result.map(item => item.key)
              this.$emit('input', this.treeDataSource[0].key)
            } else {
              this.expandedKeys = []
              this.$emit('input', null)
            }
          } else {
            this.messageUtil.warning(this.$t('m.bpm.verify.zu-zhi-ji-gou-cha-xun-shi-bai') + res.message)
            console.error(res)
          }
        }).finally(() => {
          this.loading = false
        })
      },
    }
  }
</script>
